package org.wdcode.common.codec;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.wdcode.common.constants.ArrayConstants;
import org.wdcode.common.constants.EncodingConstants;
import org.wdcode.common.exception.CustomRuntimeException;
import org.wdcode.common.util.CommonUtil;

/**
 * 解码类
 * @author WD
 * @since JDK6
 * @version 1.0 2010-06-22
 */
public final class Decode {
	/**
	 * 16进制字符串转换成字节码
	 * @param h 16进制字符串
	 * @return 转换后的字节数组
	 */
	public final static byte[] hex(String h) {
		try {
			return CommonUtil.isEmpty(h) ? ArrayConstants.BYTES_EMPTY : Hex.decodeHex(h.toCharArray());
		} catch (DecoderException e) {
			throw new CustomRuntimeException(e);
		}
	}

	/**
	 * Base64解码
	 * @param s 要解码的字符串
	 * @return 解码后字符串
	 */
	public final static byte[] base64(String s) {
		return Base64.decodeBase64(s);
	}

	/**
	 * Base64解码
	 * @param b 要解码的字节数组
	 * @return 解码后字符串
	 */
	public final static byte[] base64(byte[] b) {
		return Base64.decodeBase64(b);
	}

	/**
	 * url解码
	 * @param url 要解码的URL
	 * @return 解码后字符串
	 */
	public final static String url(String url) {
		return url(url, EncodingConstants.UTF_8);
	}

	/**
	 * url解码
	 * @param url 要解码的URL
	 * @param encoding 解码
	 * @return 解码后字符串
	 */
	public final static String url(String url, String encoding) {
		try {
			return URLCodecFactory.getURLCodec().decode(url, encoding);
		} catch (Exception e) {
			throw new CustomRuntimeException(e);
		}
	}
}
